package com.example.administrator.szb.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.QNBean;
import com.example.administrator.szb.bean.SPFBBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.Toasts;
import com.example.administrator.szb.util.TokenUtil;
import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by D N on 2017/10/9.
 */

public class SPFBActivity extends BaseActivity {
    @Bind(R.id.spfb_image_fh)
    ImageView spfbImageFh;
    @Bind(R.id.spfb_text_fb)
    TextView spfbTextFb;
    @Bind(R.id.spfb_edit_title)
    EditText spfbEditTitle;
    @Bind(R.id.spfb_image_picture)
    ImageView spfbImagePicture;
    @Bind(R.id.spfb_image_picture_up)
    ImageView spfbImagePictureUp;
    @Bind(R.id.spfb_image_picture_up_test)
    ImageView spfbImagePictureUpTest;

    private volatile boolean isCancelled = false;//是否取消上传
    String videoPath = "";
    private ProgressDialog insertDialog;
    String token = TokenUtil.getToken();
    Gson gson = new Gson();
    String url_vidio = "";
    private int REQUEST_PERMISSION_CODE = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.spfb_activity);

        ButterKnife.bind(this);
        SampleApplicationLike.getActivitiesInstance().add(this);

        insertDialog = new ProgressDialog(this);
        insertDialog.setMessage("正在插入图片...");
        insertDialog.setCanceledOnTouchOutside(false);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @OnClick({R.id.spfb_image_fh, R.id.spfb_image_picture, R.id.spfb_text_fb})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.spfb_image_fh:
                finish();
                break;
            case R.id.spfb_image_picture:
                requestCameraPermission();
                break;
            case R.id.spfb_text_fb:
                toDorequestFB();
                break;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            int grantResult = grantResults[0];
            boolean granted = grantResult == PackageManager.PERMISSION_GRANTED;


            if (!granted) {
                Toasts.show(this, "授权失败", Toast.LENGTH_SHORT);
            } else {
                chooseVideo();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestCameraPermission() {
        try {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
        } catch (Exception e) {

        }

    }

    private void toDorequestFB() {
        if (TextUtils.isEmpty(spfbEditTitle.getText().toString())) {
            DialogUtil.showSimpleDialog(SPFBActivity.this, "请输入标题");
        } else if (TextUtils.isEmpty(url_vidio)) {
            DialogUtil.showSimpleDialog(SPFBActivity.this, "选择上传的视频");
        } else {
            requestFB();
        }
    }

    private void chooseVideo() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, 1);
    }

    /**
     * 发布请求
     */
    private void requestFB() {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("title", "" + spfbEditTitle.getText().toString());
        map.put("users_id", SampleApplicationLike.getUserloginInstance().getId() + "");
        map.put("content", "" + url_vidio);
        String url = URLAddress.URLBASE + URLAddress.URL_SPFB;
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, SPFBBean.class, url, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                SPFBBean bean = (SPFBBean) response;
                if (bean.getResult() == 1) {
                    Toasts.show(SPFBActivity.this, "发布成功", Toast.LENGTH_SHORT);
                    finish();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                ContentResolver cr = this.getContentResolver();
                /** 数据库查询操作。
                 * 第一个参数 uri：为要查询的数据库+表的名称。
                 * 第二个参数 projection ： 要查询的列。
                 * 第三个参数 selection ： 查询的条件，相当于SQL where。
                 * 第三个参数 selectionArgs ： 查询条件的参数，相当于 ？。
                 * 第四个参数 sortOrder ： 结果排序。
                 */
                Cursor cursor = cr.query(uri, null, null, null, null);
                try {
                    if (cursor != null) {
                        if (cursor.moveToFirst()) {
                            // 视频ID:MediaStore.Audio.Media._ID
                            int videoId = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
                            // 视频名称：MediaStore.Audio.Media.TITLE
                            String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
                            // 视频路径：MediaStore.Audio.Media.DATA
                            String videoPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                            // 视频时长：MediaStore.Audio.Media.DURATION
                            // int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
                            // 视频大小：MediaStore.Audio.Media.SIZE
                            //long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));

                            // 视频缩略图路径：MediaStore.Images.Media.DATA
                            String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                            // 缩略图ID:MediaStore.Audio.Media._ID
                            int imageId = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
                            // 方法一 Thumbnails 利用createVideoThumbnail 通过路径得到缩略图，保持为视频的默认比例
                            // 第一个参数为 ContentResolver，第二个参数为视频缩略图ID， 第三个参数kind有两种为：MICRO_KIND和MINI_KIND 字面意思理解为微型和迷你两种缩略模式，前者分辨率更低一些。
                            //Bitmap bitmap1 = MediaStore.Video.Thumbnails.getThumbnail(cr, imageId, MediaStore.Video.Thumbnails.MICRO_KIND, null);

                            // 方法二 ThumbnailUtils 利用createVideoThumbnail 通过路径得到缩略图，保持为视频的默认比例
                            // 第一个参数为 视频/缩略图的位置，第二个依旧是分辨率相关的kind

                            Bitmap bitmap2 = ThumbnailUtils.createVideoThumbnail(imagePath, MediaStore.Video.Thumbnails.MICRO_KIND);
                            // 如果追求更好的话可以利用 ThumbnailUtils.extractThumbnail 把缩略图转化为的制定大小
//                        ThumbnailUtils.extractThumbnail(bitmap, width,height ,ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
//                            ViewGroup.LayoutParams params = spfbImagePicture.getLayoutParams();
//                            params.height = ScreenExpressionUtils.dip2px(SPFBActivity.this, 130);
//                            params.width = ScreenExpressionUtils.dip2px(SPFBActivity.this, 90);
//                            spfbImagePicture.setLayoutParams(params);
                            spfbImagePictureUp.setVisibility(View.VISIBLE);
                            File data_ = new File(imagePath);
                            Glide.with(SPFBActivity.this).load(data_).into(spfbImagePictureUp);
                            //spfbImagePicture.setImageBitmap(bitmap2);
                            videoPath = imagePath;
                            upLoadVideo(videoPath);
                        }
                        cursor.close();
                    }

                } catch (Exception e) {
                    Log.e("pdf", "onActivityResult: " + e.toString());
                }

            }
        }
    }

    /**
     * 上传视频
     *
     * @param videoPath
     */
    private void upLoadVideo(String videoPath) {
        File data = new File(videoPath);
        String key = System.currentTimeMillis() + ".mp4";
        insertDialog.setMessage("0");
        insertDialog.show();
        SampleApplicationLike.getUpLoadManager().put(data, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            Toasts.show(SPFBActivity.this, "ok", Toast.LENGTH_LONG);
                            QNBean b = gson.fromJson(info.response.toString(), QNBean.class);
                            url_vidio = "https://pic.shizhibao.net/" + b.getKey() + "";


                        } else {
                            Log.i("qiniu", "Upload Fail");
                            try {
                                Toasts.show(SPFBActivity.this, "上传失败。。。", Toast.LENGTH_SHORT);
                            } catch (Exception e) {

                            }

                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }
                        Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                    }
                }, new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            public void progress(String key, double percent) {
                                double ii = percent * 100;
                                int per = (int) ii;
                                insertDialog.setMessage(per + "%");
                                if (per == 100) {
                                    insertDialog.dismiss();
                                }
                            }
                        }, new UpCancellationSignal() {
                    public boolean isCancelled() {
                        return isCancelled;
                    }
                }));


    }

    @Override
    public void onBackPressed() {
        isCancelled = true;
        super.onBackPressed();
    }
}
